<?php
namespace library\exceptions;

/**
 * klasa bazowa wyjątków zawierająca formatowanie 
 *
 * @author Damian Jóźwiak
 */
?>

<?php
class BaseException extends \Exception{
    public  $serverCode;
    private function get_file_source($file,$line){
        $file = show_source($file, true);
        $file_raw= strip_tags(str_replace("&nbsp;", " ", $file),"<br>");
        $lines = explode("<br />", $file_raw);
        foreach ($lines as $key => &$value){
            $num=$key+1;
            $value=$num.":\t".$value;
        }
        $lines[$line-1]="<span style=\"background-color: yellow\"><b>".$lines[$line-1]."</b></span>";
        $lines_final=  array_slice($lines, $line-5,  7);
        $code = implode("<br />", $lines_final);
        return "<div style=\"background-color: #ffff99\"><code>".$code."</code></div>";
    }
    private function getTraceItem($number){
        $result="<h3>".$number.":<h3>";
        $trace = $this->getTrace()[$number];
        if (isset($trace["file"])) {
            $file=$trace["file"];
            $line =$trace["line"];
        }
        else {
            $file=$this->getFile ();
            $line =  $this->getLine();
        }
        $result.="<b>plik: </b>".$file."<br/>";
        if (isset($trace["class"])) {
            $result.="<b>klasa: </b>".$trace["class"]."<br/>";
        }
        if (isset($trace["function"])) {
        $result.="<b>funkcja: </b>".$trace["function"]."<br/>";
        }
        $result.="<b>linia: </b>".$line."<br/>";
        $result.=$this->get_file_source($file,$line);
       return $result;
    }

    public function __toString() {
        if (DEBUG){
            $result = "";
        $result.="<h1>wyjatek ".  get_class($this)."</h1>";
        $result.="<h2>w pliku ".$this->getFile()." w linii ".$this->getLine()."</h2>";
        $result.="<h3>trace:</h3>";
        foreach ($this->getTrace() as $key =>$value){
            $result.=$this->getTraceItem($key);
        }
        }
        else {
            $result="";
        }
        return $result;
    }
}
